package com.vshop.timingtask;

import com.vshop.entity.agatewaytobeijing.querydeviceorder.response.DevicePackageOrder;
import com.vshop.entity.agatewaytobeijing.querydeviceorder.response.ResponseQueryDeviceOrder;
import com.vshop.entity.alast.common.ServicePlanOrderRecord;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.agatewaytobeijing.GatewayToBeijingService;
import com.vshop.service.alast.impl.LogicAssistService;
import com.vshop.service.task.ServicePlanTaskServiceImpl;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 新版：套餐查询订单（orderId）状态同步
 *
 * @author lm
 * @date 2020/9/24 9:04
 */

@Configuration
@EnableScheduling
@RestController
@Api(value = "新版套餐查询订单状态（新流程）")
@Slf4j
public class ServicePlanQueryStatusTask {
    @Value("${system.autoTask}")
    private boolean autoTask;
    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    ServicePlanTaskServiceImpl taskService;
    @Autowired
    GatewayToBeijingService toBeijingService;
    @Autowired
    LogicAssistService logicAssistService;

    /**
     * 每天7点过2分执行
     */
    @Scheduled(cron = "0 2 7 * * ?")
    @GetMapping(value = "servicePlanQueryStatusTask")
    @Async
    public void execute() {
        if (autoTask) {
            task();
        }
    }

    public void task() {
        log.info("每天早上7点过2分执行ServicePlanQueryStatusTask开始执行！");
        //先看看有没有需要去做查询的订单列表
        List<ServicePlanOrderRecord> recordList = taskService.queryServicePlanStatus();
        if (null == recordList || recordList.isEmpty()) {
            return;
        }
        //把数据拿出来
        record:
        for (ServicePlanOrderRecord record : recordList) {
            String secret = partnerInfoService.getSecretByPartnerCode(record.getPartnerCode());
            //验证参数
            if (!checkParam(record, secret)) {
                continue;
            }

            /*说明接口从2.0更新到3.0了*/
            ResponseQueryDeviceOrder order = toBeijingService.queryDeviceOrder(record.getDeviceCode(), "", "", "", record.getPartnerCode(), secret);
            if (null == order || !Constant.RET_CODE_0000.equals(order.getCode()) || null == order.getData() || null == order.getData().getPackageOrder() || order.getData().getPackageOrder().isEmpty()) {
                continue;
            }
            //解析订单列表
            orderList:
            for (DevicePackageOrder orderList : order.getData().getPackageOrder()) {

                if (null == orderList || order.getData().getPackageOrder().isEmpty()) {
                    continue record;
                }

                if (StringUtils.isBlank(orderList.getOrderStatus()) || StringUtils.isBlank(orderList.getOrderDate())) {
                    continue orderList;
                }

                /*根据order_status订单状态：2.0旧的状态： 0-未支付； 1-未启用； 2-开始使用； 4-已取消； 3-已结束； 5-已暂停；来判定pcakageStatus激活或者未激活, order_status ！=0或者order_status ！=1  订单就算激活了*/
                /*根据order_status订单状态：3.0新的状态： 0-未启用； 1-开始使用； 2-已暂停； 3-已结束；来判定pcakageStatus激活或者未激活, orderStatus ！=0或者order_status ！=4  订单就算激活了*/
                //套餐状态：1-未激活；2-已激活；
                boolean b1 = (orderList.getOrderStatus().equals("2") || orderList.getOrderStatus().equals("3") || orderList.getOrderStatus().equals("5"))
                        && StringUtils.isNotBlank(orderList.getOrderDate()) && StringUtils.isNotBlank(orderList.getActiveDate()) && StringUtils.isNotBlank(orderList.getExpireDate());
                String status;
                /*未启用（1）,已取消（4）====肯定是未激活*/
                if (orderList.getOrderStatus().equals("1") || orderList.getOrderStatus().equals("4")) {
                    /*此时未激活*/
                    status = "1";
                } else if (b1) {
                    /*此时已激活*/
                    status = "2";
                } else {
                    status = "1";
                }
                //开始更新数据库
                Integer count = updateOrderIdStatus(status, record.getPartnerCode(), record.getDeviceCode(), record.getOrderId(), orderList.getOrderDate(), orderList.getActiveDate(), orderList.getExpireDate());
                if (count < 1) {
                    continue orderList;
                }
                log.info(record.getOrderId() + ":状态同步成功");
            }
        }
        log.info("每天早上7点过2分执行ServicePlanQueryStatusTask执行完毕！");
    }

    /**
     * 更新orderId的状态，订购时间，激活时间，预计结束时间
     *
     * @param status
     * @param partnerCode
     * @param deviceCode
     * @param orderId
     * @param orderDate
     * @param activeDate
     * @param expireDate
     * @return
     */
    private Integer updateOrderIdStatus(String status, String partnerCode, String deviceCode, String orderId, String orderDate, String activeDate, String expireDate) {
        ServicePlanOrderRecord record = new ServicePlanOrderRecord();
        record.setPartnerCode(partnerCode);
        record.setDeviceCode(deviceCode);
        record.setOrderId(orderId);
        record.setPackageStatus(status);
        record.setOrderTime(orderDate);
        record.setOrderStartDate(activeDate);
        record.setOrderExpireDate(expireDate);
        return taskService.updateOrderIdStatus(record);
    }

    /**
     * 验证所需参数的有效性
     *
     * @param record
     * @param secret
     * @return
     */
    private boolean checkParam(ServicePlanOrderRecord record, String secret) {
        boolean flag = true;
        if (StringUtils.isBlank(secret)) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPartnerCode())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getDeviceCode())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getOrderId())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getOrderNo())) {
            flag = false;
        }
        if (StringUtils.isBlank(record.getPayId())) {
            flag = false;
        }
        return flag;
    }


}
